package com.bJian.bJIanOJ.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.excel.util.StringUtils;
import com.bJian.bJIanOJ.common.ErrorCode;
import com.bJian.bJIanOJ.constant.CommonConstant;
import com.bJian.bJIanOJ.exception.BusinessException;
import com.bJian.bJIanOJ.judge.JudgeService;
import com.bJian.bJIanOJ.judge.codeSandbox.CodeSandbox;
import com.bJian.bJIanOJ.model.dto.question_submit.JudgeInfo;
import com.bJian.bJIanOJ.model.dto.question_submit.QuestionSubmitAddRequest;
import com.bJian.bJIanOJ.model.dto.question_submit.QuestionSubmitQueryRequest;
import com.bJian.bJIanOJ.model.entity.Question;
import com.bJian.bJIanOJ.model.entity.User;
import com.bJian.bJIanOJ.model.enums.QuestionSubmitStatusEnum;
import com.bJian.bJIanOJ.model.vo.QuestionVO;
import com.bJian.bJIanOJ.model.vo.question_submitVO;
import com.bJian.bJIanOJ.service.UserService;
import com.bJian.bJIanOJ.utils.SqlUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bJian.bJIanOJ.model.entity.question_submit;
import com.bJian.bJIanOJ.service.question_submitService;
import com.bJian.bJIanOJ.mapper.question_submitMapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 27658
 * @description 针对表【question_submit(题目提交)】的数据库操作Service实现
 * @createDate 2023-10-14 16:11:40
 */
@Service
public class question_submitServiceImpl extends ServiceImpl<question_submitMapper, question_submit>
        implements question_submitService {

    @Resource
    JudgeService judgeService;

    @Resource
    UserService userService;

    @Override
    public Long doSubmit(QuestionSubmitAddRequest question_submitAddRequest) {
        if (question_submitAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        question_submit questionSubmit = new question_submit();
        BeanUtils.copyProperties(question_submitAddRequest, questionSubmit);
        JudgeInfo judgeInfo = question_submitAddRequest.getJudgeInfo();
        if (judgeInfo != null) {
            questionSubmit.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        }
        boolean save = this.save(questionSubmit);
        if (!save) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "插入数据失败");
        }
        new Thread(() -> {//异步执行判题
            judgeService.doJudge(questionSubmit.getId());
        }).start();
        return questionSubmit.getQuestionId();
    }

    @Override
    public Page<question_submitVO> getquestionSubmitVOPage(Page<question_submit> question_submitPage, HttpServletRequest request) {
        List<question_submit> question_submitList = question_submitPage.getRecords();
        Page<question_submitVO> questionSubmitVOPage = new Page<>(question_submitPage.getCurrent(), question_submitPage.getSize(), question_submitPage.getTotal());
        if (CollectionUtils.isEmpty(question_submitList)) {
            return questionSubmitVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = question_submitList.stream().map(question_submit::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));

        // 填充信息
        List<question_submitVO> question_submitVOList = question_submitList.stream().map(questionSubmit -> {
            question_submitVO questionSubmitVO = question_submitVO.objToVo(questionSubmit);
            Long userId = questionSubmit.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            questionSubmitVO.setUserVO(userService.getUserVO(user));
            return questionSubmitVO;
        }).collect(Collectors.toList());
        questionSubmitVOPage.setRecords(question_submitVOList);
        return questionSubmitVOPage;
    }

    @Override
    public QueryWrapper<question_submit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<question_submit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }
        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;

    }
}




